﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace AutoCadConvert
{
    /// <summary>
    /// AutoCadTask.xaml 的交互逻辑
    /// </summary>
    public partial class AutoCadTask : UserControl                                         
    {
        private Timer[] m_Timers = new Timer[3];
        public AutoCadTask()
        {
            this.Initialized += AutoCadTask_Initialized;
            InitializeComponent();
            this.Unloaded += AutoCadTask_Unloaded;
        }
        private void AutoCadTask_Unloaded(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Trace.WriteLine("-------------unload usercontrol");
            foreach(Timer timer in m_Timers)
                if(timer!=null)
                    timer.Dispose();
        }
        private void AutoCadTask_Initialized(object sender, EventArgs e)
        {
            Task.Factory.StartNew(new Action(() =>
            {
                //等待领取任务
                InitTaskStatus(0,waitforPull, m_Timers[0]);
                //未完成任务
                InitTaskStatus(10, waitforFinish, m_Timers[1]);
                //完成任务
                InitTaskStatus(40, finish,m_Timers[2]);
            }));
            //tab页面信息初始化
            tabSoftDecorate.Children.Add(new DwgManager("软装", "type"));
            tabWinAnDoor.Children.Add(new DwgManager("门窗","type1"));
            tabHardDecorate.Children.Add(new DwgManager("硬装","type1"));
        }
        public void InitTaskStatus(int status,StackPanel sp,Timer timer)
        {
            //获取任务
            HttpManager.TaskFilter_Response ret = HttpManager.TaskFilter(1, status);
            if (ret!=null && ret.code == 1001)
            {
                foreach (HttpManager.TaskFilter_Response.TaskItem task in ret.data.tasks)
                {
                    if (!FindTask(task.id))
                    {
                        BitmapImage bitmpImg = new BitmapImage();
                        if (task.taskInput.Count() > 0)
                        {
                            WebClient client = new WebClient();
                            List<byte> lstArray = new List<byte>();
                            
                            try
                            {//文件在内存中读取
                                BinaryReader fileRed = new BinaryReader(client.OpenRead(task.taskInput[0]));
                                while (true) lstArray.Add(fileRed.ReadByte());
                            }
                            catch(EndOfStreamException ex)
                            {
                                bitmpImg.BeginInit();
                                bitmpImg.StreamSource = new MemoryStream(lstArray.ToArray());
                                bitmpImg.EndInit();
                                System.Diagnostics.Trace.WriteLine(ex.Message);
                            }
                            catch(Exception e)
                            {
                                System.Diagnostics.Trace.WriteLine(e.Message);
                            }
                        }
                        bitmpImg.Freeze();
                        TaskItem.TaskStatus estatus = (TaskItem.TaskStatus)Enum.Parse(typeof(TaskItem.TaskStatus), status.ToString());
                        this.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            //没添加的任务
                            TaskItem ti = new TaskItem(bitmpImg, estatus, task.houseName, task.description, task.taskInput[0], task.createTime, task.id, task.planInfo[0].planId);
                            ti.Margin = new Thickness(10,0,10,10);
                            ti.pullTask += Ti_pullTask;
                            sp.Children.Add(ti);
                            ResetLabel();
                        }));
                    }
                }
            }
            else
            {
                if (ret!=null&&ret.code == 2003)
                {//其他用户登陆
                    DwgConvert.Logout();
                }
                else
                {
                    System.Diagnostics.Trace.WriteLine(ret!=null?ret.msg:"**********连接异常");
                }
            }
            //执行完成后继续
            timer = new Timer(new TimerCallback(o =>
            {
                System.Diagnostics.Trace.WriteLine("run "+status+"---------------after 10s");
                InitTaskStatus(status, sp, timer);
            }), this, 10000, 0);
        }
        public void ResetLabel()
        {
            //tab1
            if (waitforPull.Children.Count > 0)
            {
                taskLabel1.Content = "任务列表 （" + (waitforPull.Children.Count) + "）";
                getAllBtn.Visibility = Visibility.Visible;
                waitforPullPic.Visibility = Visibility.Collapsed;
                scrollWaitforPull.Visibility = Visibility.Visible;
            }
            else
            {
                getAllBtn.Visibility = Visibility.Collapsed;
                waitforPullPic.Visibility = Visibility.Visible;
                scrollWaitforPull.Visibility = Visibility.Collapsed;
                taskLabel1.Content = "任务列表";
            }
            //tabHeadData1
            if (waitforPull.Children.Count > 0)
            {
                headTip.Visibility = Visibility.Visible;
                tabHeadData1.Content = waitforPull.Children.Count;
            }
            else
            {
                headTip.Visibility = Visibility.Collapsed;
            }
            //tab2
            if (waitforFinish.Children.Count > 0)
            {
                waitforFinishPic.Visibility = Visibility.Collapsed;
                scrollWaitForFinish.Visibility = Visibility.Visible;
                taskLabel2.Content = "任务列表 （" + (waitforFinish.Children.Count) + "）";
            }
            else
            {
                waitforFinishPic.Visibility = Visibility.Visible;
                scrollWaitForFinish.Visibility = Visibility.Collapsed;
                taskLabel2.Content = "任务列表";
            }
            //tab3
            if (finish.Children.Count > 0)
            {
                finishPic.Visibility = Visibility.Collapsed;
                scrollFinish.Visibility = Visibility.Visible;
                taskLabel3.Content = "任务列表 （" + (finish.Children.Count) + "）";
            }
            else
            {
                finishPic.Visibility = Visibility.Visible;
                scrollFinish.Visibility = Visibility.Collapsed;
                taskLabel3.Content = "任务列表";
            }

            //for test
            foreach (UIElement el in finish.Children)
                if (el is TaskItem)
                    (el as TaskItem).test.Visibility = Visibility.Visible;
        }
        public bool FindTask(int id)
        {
            return (bool)this.Dispatcher.Invoke(new Func<bool>(() => {
                bool bFindTask = false;
                foreach (UIElement ui in waitforPull.Children)
                {
                    if (ui is TaskItem && (ui as TaskItem).m_TaskId == id)
                        bFindTask = true;
                }
                foreach (UIElement ui in waitforFinish.Children)
                {
                    if (ui is TaskItem && (ui as TaskItem).m_TaskId == id)
                        bFindTask = true;
                }
                foreach (UIElement ui in finish.Children)
                {
                    if (ui is TaskItem && (ui as TaskItem).m_TaskId == id)
                        bFindTask = true;
                }
                return bFindTask;
            }));
        }
        private void Ti_pullTask(TaskItem item)
        {
            if (waitforPull.Children.Contains(item))
            {
                waitforPull.Children.Remove(item);
                waitforFinish.Children.Insert(0,item);
                item.getTask.Content = "开始绘制";
                item.m_Status = TaskItem.TaskStatus.WaitForFinish;
            }
            else if (waitforFinish.Children.Contains(item))
            {
                item.upLoad.Visibility = Visibility.Hidden;
                item.getTask.Visibility = Visibility.Hidden;
                waitforFinish.Children.Remove(item);
                finish.Children.Insert(0,item);
                item.m_Status = TaskItem.TaskStatus.Finish;
            }
            else
            {
                //for test
                finish.Children.Remove(item);
                System.Diagnostics.Trace.WriteLine("task error");
            }
            ResetLabel();
        }
        private void UserControl_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            this.palette.Width = this.ActualWidth;
            this.palette.Height = this.ActualHeight;
            this.tabHead1.Width = (this.ActualWidth-28) / 2;
            this.tabHead2.Width = (this.ActualWidth - 28) / 2;
            this.subTabHead1.Width = (this.ActualWidth - 10) / 3;
            this.subTabHead2.Width = (this.ActualWidth - 10) / 3;
            this.subTabHead3.Width= (this.ActualWidth - 10) / 3;
        }
        private void Button_Click_PullAllTask(object sender, RoutedEventArgs e)
        {//全部领取
            bool isError = false;
            for (int i = waitforPull.Children.Count-1; i>=0;i--)
            {
                UIElement ui = waitforPull.Children[i];
                if (ui is TaskItem)
                {
                    string response = HttpManager.TaskProcess(new int[] { (ui as TaskItem).m_PlanId }, new int[] { 10 });
                    waitforPull.Children.Remove(ui);
                    waitforFinish.Children.Insert(0,ui);
                    (ui as TaskItem).getTask.Content = "开始绘制";
                    (ui as TaskItem).m_Status = TaskItem.TaskStatus.WaitForFinish;
                    if (!response.Contains("成功"))
                        isError = true;
                }
            }
            ResetLabel();
            if (isError)
            {//提示错误
                MessageBox.Show("服务器连接异常");
            }
        }

        private void Image_MouseDown_Search(object sender, MouseButtonEventArgs e)
        {
            tabCatlog.Visibility = Visibility.Collapsed;
            scrollSearchResult.Visibility = Visibility.Visible;
            SearchCancel.Visibility = Visibility.Visible;
            CancelWidth.Width = new GridLength(30);
            //查找
            string searchText = SearchText.Text;
            SearchResult.Children.Clear();
            Task.Factory.StartNew(() =>{
                Search(searchText, 1,0);
            });
        }
        private void Search(string content,int page,int searchNum)
        {
            HttpManager.LegendSearch_Response ls = HttpManager.Legend_Search("000000", "", page);
            if (ls != null && ls.data.legends != null)
            {
                WebClient client = new WebClient();
                //查询
                List<HttpManager.LegendSearch_Response.Legend> filter = ls.data.legends.Where(o=> {
                    return o.sn.Contains(content) 
                    || o.name.Contains(content)
                    || o.typeCode.Contains(content) 
                    || o.typeName.Contains(content) 
                    || o.description.Contains(content);
                }).ToList();
                searchNum += filter.Count;
                this.Dispatcher.BeginInvoke(new Action(()=> {
                    SearchNums.Content = "共找到"+ searchNum + "个\""+content+"\"搜索结果";
                }));
                foreach (HttpManager.LegendSearch_Response.Legend legend in filter)
                {
                    string newFile = System.IO.Path.Combine(LoginInfo.instance().dwgFileDirectory, legend.sn + ".dwg");
                    if (!SearchResult.FindDwgSn(legend.sn))
                    {
                        if (!File.Exists(newFile))
                            client.DownloadFile(legend.dwgUrl, newFile);
                        SearchResult.AddDwgResource(newFile, legend, "search");
                    }
                }

                if (ls.data.count > ls.data.legends.Count() + (page - 1) * 10)
                    Search(content, page + 1, searchNum);
            }
        }
        private void SearchCancel_MouseDown_Cancel(object sender, MouseButtonEventArgs e)
        {
            SearchResult.Children.Clear();
            tabCatlog.Visibility = Visibility.Visible;
            scrollSearchResult.Visibility = Visibility.Collapsed;
            SearchCancel.Visibility = Visibility.Collapsed;
            CancelWidth.Width = new GridLength(0);
        }

        private void Border_KeyDown_Search(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter&&e.IsRepeat==false)
                Image_MouseDown_Search(null, null);
            else if (e.Key == Key.Escape && e.IsRepeat == false)
                SearchCancel_MouseDown_Cancel(null, null);
        }

        private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            TabControl tContrl = sender as TabControl;
            for(int i=0;i<tContrl.Items.Count;i++)
            {
                (tContrl.Items[i] as TabItem).Foreground = Brushes.Black;
            }

            (tContrl.SelectedItem as TabItem).Foreground = new SolidColorBrush(System.Windows.Media.Color.FromRgb(32,184,226));
        }
    }
}
